﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Web.Model;
using Portal.Cms.Model;
using Portal.Web.Utility;
using Portal.Cms.Bussiness;
using Portal.Core;
using Portal.Cms.Utility;
using System.Data;
using Portal.Systems.Model;
using Portal.Xml.Utility;

namespace Portal.Cms.Render
{
    public class PermissionCategoryConfigRenderBll
    {
        static void CheckPermission(string SiteId)
        {
            try
            {
                string UserId = WebSessionUtility.GetCurrentLoginUser().UserId;
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, SystemPermission.StaticId, SystemPermission.funcManage, SystemPermission.funcManage, UserId, true);
            }
            catch (Exception ex)
            {
                string ReturnData = "<div class=CssAccessDenied>" + ex.Message.ToString() + " <span class=CssBack><a href=\"javascript:history.back(-1);\">Quay lại</a></span></div>\r\n";
                throw new Exception(ReturnData);
            }
        }


        static WebFolderCls[] ReadingWebFolders(string SiteId, string Folder)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string XmlFile = WebConfig.GetWebPartLayout(OSiteParam);
            DataSet ds = XmlUtility.GetDataSetFromXmlFile(XmlFile);
            DataView dv = null;
            if (string.IsNullOrEmpty(Folder))
            {
                dv = new DataView(ds.Tables["WebFolder"], "ParentFolderId=''", "SortIndex ASC", DataViewRowState.CurrentRows);
            }
            else
            {
                dv = new DataView(ds.Tables["WebFolder"], "ParentFolderId='" + Folder + "'", "SortIndex ASC", DataViewRowState.CurrentRows);
            }
            WebFolderCls[] WebFolders = WebFolderParser.ParseFromDataView(dv);
            return WebFolders;
        }

        //public static bool IsChecked(
        //    string SiteId,
        //    PermissionCategoryCls[] PermissionCategorys,
        //    string WebFolderId)
        //{
        //    for (int iIndex = 0; iIndex < PermissionCategorys.Length; iIndex++)
        //    {
        //        if (PermissionCategorys[iIndex].WebFolderId.Equals(WebFolderId))
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                CheckPermission(SiteId);
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonIconRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                string RoleId = (string)WebEnvironments.Request(SiteId, "RoleId");
                RoleCls ORole = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, RoleId);
                if (ORole == null) throw new Exception("Tham số không hợp lệ!");
                
                string Html =
                    "<script language=javascript>\r\n" +
                    "   function Save(RoleId)\r\n"+
                    "   {\r\n"+
                    "       SiteId='"+SiteId+"';\r\n"+
                    "       CheckIds=document.getElementById('txtCheckedNote').value;\r\n"+
                    "       OAjaxOut = Portal.Systems.Render.PermissionCategoryManagerRenderBll.ServerSideSaveCheck(SiteId,RoleId,CheckIds).value;\r\n" +
                    "       if(OAjaxOut.Error)\r\n"+
                    "       {\r\n"+
                    "           alert(OAjaxOut.InfoMessage);\r\n"+
                    "           return;\r\n"+
                    "       }\r\n"+
                    "       alert(OAjaxOut.InfoMessage);\r\n" +
                    "   }\r\n"+
                    "</script>\r\n" +
                    " <input type=hidden style=\"width:600px;\" type=textbox id=\"txtCheckedNote\"/>\r\n"+
                    " <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n" +
                    "            <li onclick=\"javascript:Save('"+RoleId+"');\"><img class=image src=\"" + ButtonIconRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                    "            <li onclick=\"javascript:window.open('../../folder.aspx?folder=admin','_self');\"><img class=image src=\"" + ButtonIconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                    "        </ul>\r\n" +
                    " </div>\r\n" +
                    "<h3>Vị trí công việc - "+ORole.RoleName+"</h3>\r\n"+
                    "<div class=TreeHolder>\r\n" +
                        BuildCategory(SiteId,"TreeView").HtmlContent+
                    "</div>\r\n";


                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut BuildCategory(string SiteId, string TreeViewId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string XmlFile = OSiteParam.PathRoot + "\\admin\\xmldata\\news\\Portal_vi_Category.xml";
                DataSet ds = new DataSet();
                ds.ReadXml(XmlFile);
                DataView dv = new DataView(ds.Tables[0], "ParentId='0'", "", DataViewRowState.CurrentRows);
                string Html =
                    "<div class=CssListField>\r\n" +
                    "<ul id=\"" + TreeViewId + "\" class=\"TreeView\">\r\n";
                for (int iIndex = 0; iIndex < dv.Count; iIndex++)
                {
                    string Id = dv[iIndex]["Id"].ToString();
                    string Name = dv[iIndex]["Name"].ToString();
                    DataView dvSub = new DataView(ds.Tables[0], "ParentId='" + Id + "'", "", DataViewRowState.CurrentRows);
                    if (dvSub.Count > 0)
                    {
                        Html += " <li id=\"" + Id + "\" class=\"Collapsed\">\r\n" +
                                    "<a href=\"javascript:ProcessExpandCollapse('" + Id + "');\"><span id=\"spanMainFieldName" + Id + "\">" + Name + "</span></a>\r\n" +
                                        "<input type=hidden value=\"0\" id=\"txtReadSubField" + Id + "\"><ul id=\"ulSubField" + Id + "\">\r\n" +
                                            ServerSideReadingSubField(SiteId, Id).HtmlContent +
                                        "</ul>\r\n" +
                                    "</li>\r\n";
                    }
                    else
                    {
                        Html += " <li id=\"" + Id + "\" class=\"Collapsed\">\r\n" +
                                "<input type=checkbox class=checkbox onchange=\"javascript:ProcessCheckCategory('" + Id + "','')\" id=\"chk" + Id + "\" style=\"margin-right:4px;\"><span id=\"spanMainFieldName" + Id + "\">" + Name + "</span><input id=\"chkHot" + Id + "\" style=\"margin-left:5px;\" type=checkbox class=checkbox onchange=\"javascript:ProcessHotCategory('" + Id + "');\">Nóng chuyên mục\r\n" +
                                        "<input type=hidden value=\"0\" id=\"txtReadSubField" + Id + "\"><ul id=\"ulSubField" + Id + "\">\r\n" +

                                        "</ul>\r\n" +
                                    "</li>\r\n";
                    }
                }
                Html += "</ul>\r\n" +
                      "</div>\r\n";
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideReadingSubField(string SiteId, string CategoryId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string XmlFile = OSiteParam.PathRoot + "\\admin\\xmldata\\news\\Portal_vi_Category.xml";
                DataSet ds = new DataSet();
                ds.ReadXml(XmlFile);
                DataView dv = new DataView(ds.Tables[0], "ParentId='" + CategoryId + "'", "", DataViewRowState.CurrentRows);

                string Html = "";
                for (int jIndex = 0; jIndex < dv.Count; jIndex++)
                {
                    string Id = dv[jIndex]["Id"].ToString();
                    string Name = dv[jIndex]["Name"].ToString();

                    Html += " <li class=liSubTreeViewItem>\r\n" +
                            "       <input type=checkbox class=checkbox onchange=\"javascript:ProcessCheckCategory('" + Id + "','')\" id=\"chk" + Id + "\" style=\"margin-right:4px;\"><span id=\"spanMainFieldName" + Id + "\">" + Name + "</span><input id=\"chkHot" + Id + "\" style=\"margin-left:5px;\" type=checkbox class=checkbox onchange=\"javascript:ProcessHotCategory('" + Id + "');\">Nóng chuyên mục\r\n" +
                            " </li>\r\n";
                }
                OAjaxOut.RetNumber = dv.Count;
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }



        //[AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        //public static AjaxOut ServerSideSaveCheck(string SiteId, string RoleId, string CheckIds)
        //{
        //    AjaxOut OAjaxOut = new AjaxOut();
        //    try
        //    {
        //        SiteParam OSiteParam=WebEnvironments.CreateSiteParam(SiteId);
        //        string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
        //        CheckIds=CheckIds.Replace("_","");
        //        string[] Ids = CheckIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        //        PermissionCategoryCls[] PermissionCategorys = new PermissionCategoryCls[Ids.Length];
        //        for (int iIndex = 0; iIndex < PermissionCategorys.Length; iIndex++)
        //        {
        //            PermissionCategorys[iIndex] = new PermissionCategoryCls();
        //            PermissionCategorys[iIndex].AssetCode = AssetCode;
        //            PermissionCategorys[iIndex].Allow = 1;
        //            PermissionCategorys[iIndex].frkRoleId = RoleId;
        //            PermissionCategorys[iIndex].WebFolderId=Ids[iIndex].Trim();
        //        }
        //        SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).SavePermissionCategory(SiteId, AssetCode, RoleId, PermissionCategorys);
        //        OAjaxOut.InfoMessage = "Cập nhật thành công chức năng phân quyền truy cập theo vị trí";
        //    }
        //    catch (Exception ex)
        //    {
        //        OAjaxOut.Error = true;
        //        OAjaxOut.InfoMessage = ex.Message.ToString();
        //        OAjaxOut.HtmlContent = ex.Message.ToString();
        //    }
        //    return OAjaxOut;
        //}
    }
}
